﻿using System.Text.RegularExpressions;

namespace Tszy.Unlimited.Base.Extensions;

/// <summary>
/// 邮箱相关的扩展。
/// </summary>
public static class EmailExtensions
{
    /// <summary>
    /// 验证 Email 的正则表达式。
    /// </summary>
    private static readonly Regex _emailExpression = new(@"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$",
        RegexOptions.Singleline | RegexOptions.Compiled);

    ///// <summary>
    ///// 是否电子邮箱。
    ///// </summary>
    ///// <param name="target">当前字符串。</param>
    ///// <returns>是否电子邮箱。</returns>
    //public static bool IsEmail(this string target) => !string.IsNullOrEmpty(target) && _emailExpression.IsMatch(target);

    /// <summary>
    /// 验证邮箱。
    /// </summary>
    /// <param name="source">当前字符串。</param>
    /// <returns>是否邮箱。</returns>
    public static bool IsEmail(this string source)
    {
        if (string.IsNullOrWhiteSpace(source)) return false;

        if (source.Length < 5)
        {
            return false;
        }

        if (!source.Contains('@'))
        {
            return false;
        }

        if (source.StartsWith("@") || source.EndsWith("@"))
        {
            return false;
        }

        var emailArray = source.Split('@');

        if (emailArray.Length < 2)
        {
            return false;
        }

        var first = emailArray[0];
        var last = emailArray[1];

        if (string.IsNullOrWhiteSpace(first))
        {
            return false;
        }

        if (string.IsNullOrWhiteSpace(last))
        {
            return false;
        }

        if (!last.Contains('.'))
        {
            return false;
        }

        if (last.StartsWith(".") || last.EndsWith("."))
        {
            return false;
        }

        return true;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static string GetEmailToLower(this string source)
    {
        if (string.IsNullOrWhiteSpace(source))
            return source;

        if (!_emailExpression.IsMatch(source))
            return source;

        var emailArray = source.Split('@');

        if (emailArray.Length != 2)
        {
            return source;
        }

        var first = emailArray[0];
        var last = emailArray[1];

        if (!string.IsNullOrWhiteSpace(first) && !string.IsNullOrWhiteSpace(last))
        {
            return first + "@" + last.ToLower();
        }

        return source;
    }

    /// <summary>
    /// 判断当前邮箱是否与指定的邮箱相匹配。
    /// </summary>
    /// <param name="source">当前邮箱。</param>
    /// <param name="email">目标邮箱。</param>
    /// <returns>相同则返回 True，否则返回 False。</returns>
    public static bool EqualEmail(this string source, string email)
    {
        var current = source.GetEmailToLower();
        var target = email.GetEmailToLower();

        return current == target;
    }
}
